package com.GlobalPaint.app.ui.Mine.setting;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.LogBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.TalentBean;
import com.GlobalPaint.app.bean.UpdateTO;
import com.GlobalPaint.app.utils.CleanMessageUtil;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.DownloadService;
import com.blankj.utilcode.utils.AppUtils;
import com.blankj.utilcode.utils.SPUtils;
import com.google.gson.Gson;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import static com.GlobalPaint.app.utils.DataManager.city;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener{

    private ImageView img_kg;
    private int num = 0;
    private ImageView iv_goback;
    private TextView tv_common_center;
    private RelativeLayout rl_password;
    private RelativeLayout rl_regard;
    private TextView tv_clear;
    private RelativeLayout rl_cache;
    private SPUtils spUtils;
    private LogBean logBean;
    private boolean kaiguan;
    private   PushAgent mPushAgent;
    private TalentBean bean;
    public static final int CMD_DOWN_APP = 0x0001;
    public static final int GET_TOKEN =0x0004;//上传地址和推送的token
    public static final int GET_TOKEN_NULL =0x0003;//上传地址和推送的token
    public static final int GET_ALIAS =0x0005;//上传友盟
    public static final int GET_ALIAS_NULL=0x0006;//上传友盟
    public static final int CMD_CHECKAPP_UPDATE = 0x0002; //版本更新
    private UpdateTO updateTO;
    private Handler mhandler = new Handler() {
        public void handleMessage(Message message) {
            switch (message.what) {
                case GET_TOKEN_NULL:
                    String url2= Constants.JASON_SERVICE_URL+"user/uploadAliasInfo?userId="
                            + DataManager.userEntity.getUserId()+"&userName="+DataManager.userEntity.getUserName()
                            +"&deviceToken="+DataManager.deviceToken+"&alias="+""+"&sessionId="+
                            DataManager.userEntity.getCookie();
                    Log.d("SettingActivity", "url2==" +url2);
                    Log.d("SettingActivity", "GET_TOKEN==" +DataManager.deviceToken +"城市名称=="+city);
                    DataManager.getInst().getHttpRequestJsonClass(url2, DataManager.userEntity.getCookie(), TalentBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            bean = (TalentBean) o;
                            if(bean.getStatus()==1){
                                mhandler.sendEmptyMessage(GET_ALIAS_NULL);
                                Log.d("mainActivity", "GET_TOKEN:+onSuccess");
                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                        }
                    });
                    break;
                case GET_TOKEN:
                    String url3= Constants.JASON_SERVICE_URL+"user/uploadAliasInfo?userId="
                            + DataManager.userEntity.getUserId()+"&userName="+DataManager.userEntity.getUserName()
                            +"&deviceToken="+DataManager.deviceToken+"&alias="+city+"&sessionId="+
                            DataManager.userEntity.getCookie();
                    Log.d("SettingActivity", "url3==" +url3);
                    Log.d("SettingActivity", "GET_TOKEN==" +DataManager.deviceToken +"城市名称=="+city);
                    DataManager.getInst().getHttpRequestJsonClass(url3, DataManager.userEntity.getCookie(), TalentBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            bean = (TalentBean) o;
                            if(bean.getStatus()==1){
                                mhandler.sendEmptyMessage(GET_ALIAS);
                                Log.d("mainActivity", "GET_TOKEN:+onSuccess");
                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                        }
                    });
                    break;
                case GET_ALIAS:
                    mPushAgent.addAlias(city, "qiLian", new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            Log.d("DDDDDDD", "GET_TOKEN:+onSuccess");
                        }

                    });
                    break;
                case GET_ALIAS_NULL:
                    mPushAgent.removeAlias(city, "qiLian", new UTrack.ICallBack(){
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            Log.d("DDDDDDD", "GET_TOKEN_null:+onSuccess");
                        }
                    });
                    break;
                case CMD_CHECKAPP_UPDATE:

                    String urlString = Constants.JASON_SERVICE_URLSJ + "CommonFunction/app/appupdate/getAppInfo?type=android&roleid=1";
                    DataManager.getInst().getHttpRequestJsonClass(urlString, Constants.key, UpdateTO.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            updateTO = (UpdateTO) o;

                            if (TextUtils.equals(updateTO.getData().get(0).getVername(), String.valueOf("V"+AppUtils.getAppInfo(getApplicationContext()).getVersionName()))) {
                                Toast.makeText(SettingActivity.this, "已经是最新版本", Toast.LENGTH_SHORT).show();

                            } else {
                               // updateTO.getMsg()= updateTO.getMsg().replace("@", "\n");

                                    AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                                    builder.setMessage( "发现有新版本 是否升级");
                                    builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            mhandler.sendEmptyMessage(CMD_DOWN_APP);

                                        }
                                    });
                                    builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();

                                        }
                                    });
                                    //不关闭写法
                                    builder.setCancelable(false);
                                    builder.create().show();


                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {
//                            CommUtility.ShowMsgShort(context, error.msg);
                            Toast.makeText(SettingActivity.this, "获取最新版本失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
                case CMD_DOWN_APP:
                    Intent intent = new Intent(getApplicationContext(), DownloadService.class);
                    intent.putExtra("updateinfo", new Gson().toJson(updateTO));
                    startService(intent);
                    break;
            }
        }
    };
    private RelativeLayout rl_sj;
    private TextView tv_sj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
      mPushAgent = PushAgent.getInstance(getApplicationContext());
        spUtils = new SPUtils(DataManager.context, "login");
        initView();
    }

    private void initView() {
        img_kg = (ImageView) findViewById(R.id.img_kg);
        img_kg.setOnClickListener(this);
        iv_goback = (ImageView) findViewById(R.id.iv_goback);
        iv_goback.setOnClickListener(this);
        tv_common_center = (TextView) findViewById(R.id.tv_common_center);
        tv_common_center.setText("系统设置");
        rl_password = (RelativeLayout) findViewById(R.id.rl_password);
        rl_password.setOnClickListener(this);
        rl_regard = (RelativeLayout) findViewById(R.id.rl_regard);
        rl_regard.setOnClickListener(this);
        tv_clear = (TextView) findViewById(R.id.tv_clear);
        try {
            tv_clear.setText(CleanMessageUtil.getTotalCacheSize(getApplicationContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        rl_cache = (RelativeLayout) findViewById(R.id.rl_cache);
        rl_cache.setOnClickListener(this);
        //判断开关
        kaiguan = spUtils.getBoolean("kaiGuai");
        if(kaiguan==true){
            mhandler.sendEmptyMessage(GET_TOKEN);
            img_kg.setImageResource(R.drawable.swich_on);
        }else {
            mhandler.sendEmptyMessage(GET_TOKEN_NULL);
            img_kg.setImageResource(R.drawable.swich_off);
        }
        rl_sj = (RelativeLayout) findViewById(R.id.rl_sj);
        rl_sj.setOnClickListener(this);
        tv_sj = (TextView) findViewById(R.id.tv_sj);
        tv_sj.setText(String.valueOf(AppUtils.getAppInfo(getApplicationContext()).getVersionName()));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_kg:
                num++;
                if (num % 2 == 0) {
                    spUtils.putBoolean("kaiGuai",false);
                   img_kg.setImageResource(R.drawable.swich_off);

                }
                else {
                 spUtils.putBoolean("kaiGuai",true);
                    img_kg.setImageResource(R.drawable.swich_on);
                }
                break;
            case R.id.iv_goback:
                finish();
                break;
            case R.id.rl_cache:
                CleanMessageUtil.clearAllCache(getApplicationContext());
                try {
                    tv_clear.setText(CleanMessageUtil.getTotalCacheSize(getApplicationContext()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.rl_password:
                Intent intent=new Intent(SettingActivity.this,PasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_regard:
                Intent intent2=new Intent(SettingActivity.this,RegardActivity.class);
                startActivity(intent2);
                break;
            case R.id.rl_sj:
                mhandler.sendEmptyMessage(CMD_CHECKAPP_UPDATE);
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
